package com.yonyou.sto.modules.ims.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yonyou.sto.common.api.CommonResult;
import com.yonyou.sto.modules.ims.dto.TaxItemDto;
import com.yonyou.sto.modules.ims.mapper.ImsTaxItemMapper;
import com.yonyou.sto.modules.ims.model.ImsTaxItem;
import com.yonyou.sto.modules.ims.model.ImsTaxItemPartyRelation;
import com.yonyou.sto.modules.ims.service.ImsPartyAdminRelationService;
import com.yonyou.sto.modules.ims.service.ImsTaxItemPartyRelationService;
import com.yonyou.sto.modules.ims.service.ImsTaxItemService;
import com.yonyou.sto.modules.ums.model.UmsAdmin;
import com.yonyou.sto.modules.ums.service.UmsAdminRoleRelationService;
import com.yonyou.sto.modules.ums.service.UmsAdminService;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author aegon
 * @since 2020-09-15
 */
@Service
public class ImsTaxItemServiceImpl extends ServiceImpl<ImsTaxItemMapper, ImsTaxItem> implements ImsTaxItemService {

    @Resource
    private ImsTaxItemMapper imsTaxItemMapper;

    @Resource
    private UmsAdminService adminService;

    @Resource
    private ImsPartyAdminRelationService imsPartyAdminRelationService;

    @Resource
    private ImsTaxItemPartyRelationService imsTaxItemPartyRelationService;

    @Resource
    private UmsAdminRoleRelationService roleRelationService;

    @Override
    public boolean create(TaxItemDto dto) {
        ImsTaxItem imsTaxItem = new ImsTaxItem();
        BeanUtil.copyProperties(dto, imsTaxItem);
        imsTaxItem.setCreateTime(new Date());
        imsTaxItem.setStatus(1);
        imsTaxItem.setSort(0);

        baseMapper.insert(imsTaxItem);
//        this.relationTaxItemParty(imsTaxItem.getId(), dto.getParty());
        return true;
    }

    @Override
    public CommonResult<String> updateParty(TaxItemDto dto) {
        this.relationTaxItemParty(dto.getId(), dto.getParty());
        return CommonResult.success("修改成功");
    }

    public int relationTaxItemParty(Long id, List<Long> partyIds){
        int count = partyIds == null ? 0 : partyIds.size();
        //先删除原来的关系
        QueryWrapper<ImsTaxItemPartyRelation> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(ImsTaxItemPartyRelation::getTaxItemId, id);
        imsTaxItemPartyRelationService.remove(wrapper);
        //建立新关系
        if (!CollectionUtils.isEmpty(partyIds)) {
            List<ImsTaxItemPartyRelation> list = new ArrayList<>();
            for (Long PartyId : partyIds) {
                ImsTaxItemPartyRelation PartyRelation = new ImsTaxItemPartyRelation();
                PartyRelation.setTaxItemId(id);
                PartyRelation.setPartyId(PartyId);
                list.add(PartyRelation);
            }
            imsTaxItemPartyRelationService.saveBatch(list);
        }
        return count;
    }

    @Override
    public boolean delete(Long id) {
        ImsTaxItem imsTaxItem = new ImsTaxItem();
        imsTaxItem.setId(id);
        imsTaxItem.setStatus(0);
        imsTaxItemMapper.updateById(imsTaxItem);
        return true;
    }

    @Override
    public Page<ImsTaxItem> list(Principal principal, String keyword, Integer pageSize, Integer pageNum) {

        // 当前用户->组织->税率
        UmsAdmin umsAdmin = adminService.getAdminByUsername(principal.getName());
        List<String> roleIds = roleRelationService.getRoleIdsByAdminId(umsAdmin.getId());

        Page<ImsTaxItem> page = new Page<>(pageNum, pageSize);
        QueryWrapper<ImsTaxItem> wrapper = new QueryWrapper<>();
        LambdaQueryWrapper<ImsTaxItem> lambda = wrapper.lambda();
        lambda.eq(ImsTaxItem::getStatus, 1);

        if (CollUtil.isNotEmpty(roleIds) && !roleIds.contains(5L)) {
            List<Long> partyIds = imsPartyAdminRelationService.getPartyIdsByAdminId(umsAdmin.getId());
            List<Long> taxIds = imsTaxItemPartyRelationService.getTaxIdsByPartyIds(partyIds);
            lambda.in(ImsTaxItem::getId, taxIds);
        }if (StrUtil.isNotEmpty(keyword)) {
            lambda.and(wrappers -> wrappers.like(ImsTaxItem::getTaxItemCategoryCode, keyword)
                    .or().like(ImsTaxItem::getTaxItemFirstCategory, keyword)
                    .or().like(ImsTaxItem::getTaxItemSecondCategory, keyword)
                    .or().like(ImsTaxItem::getTaxItemName, keyword));
        }
        lambda.orderByAsc(ImsTaxItem::getTaxItemCategoryCode);
        return page(page, wrapper);
    }

    @Override
    public CommonResult<String> importTax(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        if (!fileName.matches("^.+\\.(?i)(xlsx)$")) {
            return CommonResult.failed("请上传excel2007之后的xlsx文件");
        }

        try {
            XSSFWorkbook xssf = new XSSFWorkbook(file.getInputStream());
            int numberOfSheets = xssf.getNumberOfSheets();

            List<ImsTaxItem> items = new ArrayList<>();
            for (int i = 0; i < numberOfSheets; i++) {// 表
                XSSFSheet sheet = xssf.getSheetAt(i);
                int physicalNumberOfRows = sheet.getPhysicalNumberOfRows();
                for (int j = 0; j < physicalNumberOfRows; j++) {// 行
                    if (j == 0) continue;
                    XSSFRow row = sheet.getRow(j);
                    int physicalNumberOfCells = row.getPhysicalNumberOfCells();

                    ImsTaxItem item = new ImsTaxItem();
                    Field[] f = item.getClass().getDeclaredFields();

                    for (int k = 0; k < physicalNumberOfCells; k++) {// 单元格
                        row.getCell(k).setCellType(Cell.CELL_TYPE_STRING);
                        XSSFCell cell = row.getCell(k);
                        String stringCellValue = cell.getStringCellValue();
                        // 此方法要求导入格式必须正确 索引从1开始
                        String attributeName = f[k + 3].getName();
                        String methodName = attributeName.substring(0, 1).toUpperCase() + attributeName.substring(1);
                        if ("taxItemRate".equals(attributeName)){
                            Method setMethod = item.getClass().getMethod("set" + methodName, BigDecimal.class);
                            setMethod.invoke(item, new BigDecimal(stringCellValue));
                        }else {
                            Method setMethod = item.getClass().getMethod("set" + methodName, String.class);
                            setMethod.invoke(item, stringCellValue);
                        }
                        item.setCreateTime(new Date());
                        item.setStatus(1);
                    }
                    items.add(item);
                }
            }
            boolean b = saveBatch(items);
            return CommonResult.success("上传文件成功");
        } catch (IOException | NoSuchMethodException | IllegalAccessException | InvocationTargetException | NullPointerException e) {
            e.printStackTrace();
            return CommonResult.failed("上传文件格式不正确");
        }
    }

    @Override
    public CommonResult<String> updateTax(Long id, TaxItemDto dto) {
        ImsTaxItem imsTaxItem = new ImsTaxItem();
        imsTaxItem.setId(id);
        BeanUtil.copyProperties(dto, imsTaxItem);
        baseMapper.updateById(imsTaxItem);
        return CommonResult.success("修改成功");
    }

    @Override
    public CommonResult<TaxItemDto> info(Long id) {
        ImsTaxItem byId = getById(id);
        List<Long> partyIds = imsTaxItemPartyRelationService.getPartyIdsByTaxId(id);
        TaxItemDto dto = new TaxItemDto();
        BeanUtil.copyProperties(byId, dto);
        dto.setParty(partyIds);
        return CommonResult.success(dto);
    }


}
